<template>
  <div v-if="formLoaded">
    <page-banner v-if="showBanner && bannerPosition==='top'" ref="pageBanner" :banner-setting="bannerSetting" />
    <complex-form2
      v-if="layout"
      ref="complexForm"
      :class="[
        'complex-form',
        {
          'is-fixed': actionbarFixed
        }]"
      :res-data="resData"
      :layout="layout"
      :fields="fields"
      :data="form"
      :btn="btn"
      :disabled="isDetail"
      :field-rule="fieldRule"
      :complex-config="formConfig"
      :p-instance="this"
    />
    <custom-form-async
      v-else
      ref="customForm"
      :class="[
        'custom-from',
        {
          'is-fixed': actionbarFixed
        }]"
      :res-data="resData"
      :form="form"
      :form-rows="formRows"
      :field-rule="fieldRule"
    />
    <page-banner v-if="showBanner && bannerPosition==='bottom'" ref="pageBanner" :banner-setting="bannerSetting" />
    <div
      class="btn-container actionbar"
      :class="[{
        'is-fixed': actionbarFixed
      }]"
    >
      <el-button v-if="!isDetail" size="small" @click="handleClose('back')">{{ backText }}</el-button>
      <el-button v-if="!isDetail && showSave" type="primary" size="small" @click="handleSave">{{ saveText }}</el-button>
      <el-button v-if="!isDetail && showSubmit" type="primary" size="small" @click="handleSubmit">{{ submitText }}</el-button>
      <table-operate :btns="formToolbarBtns" is_formpage class="form-operate" style="display:inline-block;" size="small" />
      <el-button v-if="isDetail" @click="handleClose('close')">{{ closeText }}</el-button>
    </div>
  </div>
</template>

<script>
import baseForm from '@admin/packages/table-operate/src/baseForm.vue'
import main from './mixins/main'
import banner from './mixins/banner'
import {
  getFormDataFromId
} from '@admin/api/common.js'
import {
  getRoute,
  getUrlParam,
  windowClose
} from '@admin/utils/index'
import {
  getPRoute
} from '@admin/utils/route'
import {
  isFunction
} from '@admin/utils/index'
export default {
  name: 'Tem1140',
  components: {
    CustomFormAsync: () => import('@admin/packages/custom-form/src/async')
  },
  extends: baseForm,
  mixins: [main, banner],
  data() {
    return {
      isPageForm: true
    }
  },
  computed: {
    btn: function() {
      return {
        code: window.$CD.pageId
      }
    },
    formToolbarBtns: function() {
      // 工具栏按钮来源：1.页面配置工具栏 2.表单配置工具栏
      const pageToolbarBtns = this.btns.filter((btn) => ['10'].includes(btn.disType))
      const formToolbarBtns = this.customFormBtns.filter(i => ['120'].includes(i.disType))
      return [...pageToolbarBtns, ...formToolbarBtns]
    },
    formParam: function() {
      // 自定义业务id，不从url上获取
      if (this.id) {
        return {
          id: this.id
        }
      }
      let query = JSON.parse(JSON.stringify(this.$route.query || {}))
      if(query.parentDataId && !query.id){
        query.id = query.parentDataId
        delete query.parentDataId
      }
      return query
    },
    isDetail: function() {
      return !!this.formSetting.readonly || this.resData.readonly == 1
    },
    formId: function() {
      return this.formSetting.formId
    },
    actionbarFixed: function() {
      return this.formConfig.actionbarFixed || false
    },
    parentCode: function() {
      return this.formConfig.pCode || this.pCode || ''
    }
  },
  watch: {
    dialogName: function(newName) {
      console.log(newName)
    }
  },
  created: function() {

  },
  mounted: function() {
    this.initForm(this.formParam)
  },
  methods: {
    reloadForm() {
      const params = JSON.parse(JSON.stringify(this.formParam))
      if (this.saveCount && !params['id']) {
        params['id'] = this.resData.data.id
      }
      this.initForm(params)
    },
    // 新建表单
    createForm() {
      const params = JSON.parse(JSON.stringify(this.formParam))
      delete params.id
      this.initForm(params).finally(()=>{
        setTimeout(()=>{
          this.saveCount = 0
        })
      })
    },
    // 请求接口初始化
    initForm(extendParam = {}) {
      let param = {
        pageId: window.$CD.pageId,
        formId: this.formId
      }
      param = Object.assign(param, extendParam)
      this.formLoaded = false
      // 请求接口前回调
      const pageId = window.$CD.pageId
      if (window.$CD && window.$CD.callback && window.$CD.callback[pageId] && window.$CD.callback[pageId].beforeRequestForm) {
        window.$CD.callback[pageId].beforeRequestForm({ param })
      }
      const saveCount = this.saveCount
      return getFormDataFromId(param).then(res => {
        this.openFormDialog(res, this.btn)
      }).finally(() => {
        // 保留原saveCount,刷新表单时不更新
        this.saveCount = saveCount
      })
    },
    toLastView(visitedViews, view) {
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        this.$router.push(latestView.fullPath)
      } else {
        if (view.name === 'Dashboard') {
          this.$router.replace({ path: '/redirect' + view.fullPath })
        } else {
          this.$router.push('/')
        }
      }
    },
    redirectNav(code, query = {}) {
      const route = getRoute(code)
      this.$router.push({
        path: route.path,
        query: query
      })
    },
    handleClose(type = 'close') {
      /**
       * 关闭方法
       * 优先级：
       * 0. _layout=0,0时关闭当前页面
       * 0.1 支持自定义逻辑
       * 1. 表单配置父页面code
       * 2. 设置允许返回按钮，会在路由上拼接_pcode
       * 3. 默认从缓存中获取配置
       * 4. 返回上次打开的页面
       */
      console.log(getUrlParam('_layout'))
      if (getUrlParam('_layout') === '0,0') {
        windowClose()
        return
      }
      const view = this.$route
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        const done = () => {
          const pRoute = getPRoute(this.code)
          if (this.parentCode) {
            this.redirectNav(this.parentCode)
          } else if (Object.keys(pRoute).length) {
            this.$router.push({
              path: pRoute.path,
              query: pRoute.query
            })
          } else {
            this.toLastView(visitedViews, view)
          }
        }
        debugger
        if (type === 'close' && window.$CD && isFunction(window.$CD[this.formConfig.formBeforeCloseFunc])) {
          window.$CD[this.formConfig.formBeforeCloseFunc]({ done, instance: this })
        } else {
          done()
        }
      })
    },
    // 暂存-只保存数据
    saveFormData() {
      return this.formZanSave()
    },
    // 暂存
    handleSave() {
      this.handleSaveForm({
        dialog: false,
        params: {
          pageId: window.$CD.pageId,
          formId: this.formId
        },
        submit: false
      })
    },
    // 提交
    handleSubmit(options) {
      const fullOptions = Object.assign({}, {
        done: this.handleClose,
        dialog: false,
        params: {
          pageId: window.$CD.pageId,
          formId: this.formId
        }
      }, options)
      this.handleConfirm(fullOptions)
    }
  }
}
</script>
<style lang="scss" scoped>
.btn-container{
  text-align: center;
  margin-top: 8px;
  .form-operate{
    margin-left: 16px;
  }
}
.complex-form{
  &.is-fixed{
    margin-bottom: 80px;
  }
}
.custom-from{
  &.is-fixed{
    margin-bottom: 80px;
  }
}
.actionbar{
  .el-button+.el-button{
    margin-left: 16px;
  }
  ::v-deep .table-operate-container{
    .btn-wraper{
      margin-right: 16px;
    }
  }
  &.is-fixed{
    position: fixed;
    bottom: 0;
    width: calc(100% - var(--g-sidebar-actual-width));
    transform: translateX(-20px);
    padding: 20px;
    z-index: 4;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    ::v-deep .table-operate-container{
      margin-bottom: 0;
    }
  }
}
</style>
<style lang="scss" scoped>
html.screen-small{
  .complex-form.is-fixed{
    margin-bottom: 70px;
  }
  .actionbar.is-fixed{
    padding: 10px 0;
    ::v-deep .table-operate-container{
      margin-bottom: 0;
    }
  }
}
html.screen-mini{
  .complex-form.is-fixed{
    margin-bottom: 60px;
  }
  .actionbar.is-fixed{
      padding: 5px 0;
      ::v-deep .table-operate-container{
        margin-bottom: 0;
      }
  }
}
</style>
